package com.kkb.controller;

import com.alibaba.fastjson.JSON;
import com.kkb.bean.*;
import com.kkb.mvc.ResponseBody;
import com.kkb.service.ExpressService;
import com.kkb.service.UserService;
import com.kkb.utils.DateFormatUtil;
import com.kkb.utils.JSONUtil;
import com.kkb.utils.UserUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

public class WxExpressController {
    @ResponseBody("/wx/expressFindByPhone.do")
    public String wxExpressList(HttpServletRequest request, HttpServletResponse response){

        User userInfo = UserUtil.getUserInfo(request.getSession());
        List<Express> expresses = ExpressService.findByPhoneNumber(userInfo.getPhoneNumber());
        // 数据转换
        ArrayList<TableExpress> newAll = new ArrayList<>();
        for (Express e : expresses) {
            String code = e.getCode()== null ? "已取件": e.getCode();
            String outtime = e.getOutTime()== null ? "未出库": DateFormatUtil.format(e.getOutTime());
            String intime = DateFormatUtil.format(e.getInTime());
            String status = e.getStatus() == 0 ? "未取件":"已取件";
            TableExpress tableExpress = new TableExpress(e.getId(),e.getNumber(),e.getUsername(),e.getUserPhone(),e.getCompany(),code,intime,outtime,status,e.getSysPhone());
            newAll.add(tableExpress);
        }


        Message msg = null;
        // jdk8 的 list 新特性 stream流
        if (newAll.size() == 0){
            // 没有数据
            msg = new Message(-1,"没有快递消息");
        } else{
            // 获得未取件的快递
            Stream<TableExpress> s0 = newAll.stream().filter(express -> {
                if (express.getStatus().equals("未取件"))
                    // 未取件
                    return true;
                else return false;
            }).sorted((o1, o2) -> {
                // 根据 时间大小排序
                return DateFormatUtil.format(o1.getInTime()) > DateFormatUtil.format(o2.getInTime()) ? 1 : -1;
            });
            // 获得已取件的快递
            Stream<TableExpress> s1 = newAll.stream().filter(express -> {
                if (express.getStatus().equals("已取件"))
                    // 已取件
                    return true;
                else return false;
            }).sorted((o1, o2) -> {
                // 根据 时间大小排序
                return DateFormatUtil.format(o1.getInTime()) > DateFormatUtil.format(o2.getInTime()) ? 1 : -1;
            });
            Object[] express0 = s0.toArray();
            Object[] express1 = s1.toArray();
            // 保存数据
            HashMap map = new HashMap<>();
            map.put("status0",express0);
            map.put("status1",express1);
            msg = new Message(0,map);
        }
        return JSONUtil.toJSON(msg);
    }

    /**
     * 展示所有未取件的用户快递
     * @param request
     * @param response
     * @return
     */
    @ResponseBody("/wx/userExpress.do")
    public String userExpressList(HttpServletRequest request, HttpServletResponse response){
        String userPhone = request.getParameter("userPhone");
//        int status = Integer.parseInt(request.getParameter("status"));
        List<Express> list = ExpressService.findByPhoneAndStatus0(userPhone,0);
        // 数据转换
        String newStatus = "";
        String outtime = "";
        ArrayList<TableExpress> newAll = new ArrayList<>();
        for (Express e : list) {
            String code = e.getCode()== null ? "已取件": e.getCode();
            String intime = DateFormatUtil.format(e.getInTime());
            TableExpress tableExpress = new TableExpress(e.getId(),e.getNumber(),e.getUsername(),e.getUserPhone(),e.getCompany(),code,intime,outtime,newStatus,e.getSysPhone());
            newAll.add(tableExpress);
        }
        Message m = null;
        if (newAll.size()==0){
            m = new Message(-1,"未查询到快递");
        } else {
            m = new Message(0,"查询成功",newAll);
        }

        return JSONUtil.toJSON(m);
    }

    /**
     * 修改快递状态，将未取件-》取件
     * @param request
     * @param response
     * @return
     */
    @ResponseBody("/wx/updateStatus.do")
    public String updateStatus(HttpServletRequest request, HttpServletResponse response) {
        String code = request.getParameter("code");
        System.out.println(code);
        boolean b = ExpressService.updateStatus(code);
        Message msg = null;
        if (b){
            msg = new Message(0,"取件成功");
        } else {
            msg = new Message(-1,"取件失败,请重新操作");
        }
        return JSONUtil.toJSON(msg);
    }

    @ResponseBody("/wx/findByCode.do")
    public String findByCode(HttpServletRequest request, HttpServletResponse response){
        String code = request.getParameter("code");
        Express e = ExpressService.findByCode(code);
        TableExpress tableExpress = null;
        Message msg = null;
        if (e!=null){
            String inTime = DateFormatUtil.format(e.getInTime());
            String outTime = e.getOutTime() == null ? "未出库": DateFormatUtil.format(e.getOutTime());
            String status = e.getStatus() == 0 ? "未取件":"已取件";
            tableExpress = new TableExpress(e.getId(), e.getNumber(), e.getUsername(), e.getUserPhone(), e.getCompany(), e.getCode(), inTime, outTime, status, e.getSysPhone());
            msg = new Message(0,"查询成功",tableExpress);
        } else{
           msg = new Message(-1,"查询失败");
        }
        return JSONUtil.toJSON(msg);
    }

    @ResponseBody("/wx/isOneNumber.do")
    public String isOneNumber(HttpServletRequest request , HttpServletResponse response){

        String number = request.getParameter("number");
        boolean res = ExpressService.isOneNumber(number);
        Message m = null;
        if (res){
            // 存在
            m = new Message(-1);
        } else {
            m = new Message(0);
        }
        return JSON.toJSONString(m);
    }

    @ResponseBody("/wx/insert.do")
    public String insert(HttpServletRequest request , HttpServletResponse response){
        String number = request.getParameter("number");
        String company = request.getParameter("company");
        String username = request.getParameter("username");
        String userPhone = request.getParameter("userPhone");
        Express e = new Express();
        e.setNumber(number);
        e.setCompany(company);
        e.setUsername(username);
        e.setUserPhone(userPhone);
        // 录入人手机号
        e.setSysPhone(UserUtil.getUserPhone(request.getSession()));
        boolean res = ExpressService.insert(e);
        Message m = null;
        if (res){
            m = new Message(0,"录入成功");
        } else{
            m = new Message(-1,"录入失败");
        }
        return JSONUtil.toJSON(m);
    }

    @ResponseBody("/wx/lazyBoard.do")
    public String lazyBoard(HttpServletRequest request , HttpServletResponse response){
        Map<String, List<RankingExpress>> map = UserService.rankingByAll();
        Message msg = null;
        if (map.isEmpty()){
            msg = new Message(-1,"获取榜单失败");
        } else{
            msg = new Message(0,"查询成功",map);
        }
        return JSONUtil.toJSON(msg);
    }

    @ResponseBody("/wx/findExpressByNum.do")
    public String findExpress(HttpServletRequest request , HttpServletResponse response){
        String number = request.getParameter("number");
        Express e = ExpressService.findByNumber(number);
        TableExpress tableExpress = null;
        Message msg = null;
        if (e!=null){
            String inTime = DateFormatUtil.format(e.getInTime());
            String outTime = e.getOutTime() == null ? "未出库": DateFormatUtil.format(e.getOutTime());
            String status = e.getStatus() == 0 ? "未取件":"已取件";
            tableExpress = new TableExpress(e.getId(), e.getNumber(), e.getUsername(), e.getUserPhone(), e.getCompany(), e.getCode(), inTime, outTime, status, e.getSysPhone());
            msg = new Message(0,"查询成功",tableExpress);
        } else{
            msg = new Message(-1,"查询失败");
        }
        return JSONUtil.toJSON(msg);
    }



}
